package com.example.singing.view;

import com.example.singing.manager.CompetitionManager;
import com.example.singing.manager.ScoreManager;
import com.example.singing.manager.TeamManager;
import com.example.singing.model.Competition;
import com.example.singing.util.AlertUtil;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.FileChooser;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 比赛管理界面
 */
public class CompetitionView {
    private VBox view;
    private CompetitionManager competitionManager;
    private ScoreManager scoreManager;
    private TeamManager teamManager;
    private VBox competitionListContainer; // 用于容纳比赛卡片的容器
    private List<Image> backgroundImages; // 存储背景图片

    public CompetitionView() {
        this.competitionManager = new CompetitionManager();
        this.scoreManager = new ScoreManager();
        this.teamManager = new TeamManager();
        loadBackgroundImages();
        createView();
    }

    /**
     * 加载背景图片资源
     */
    private void loadBackgroundImages() {
        backgroundImages = new ArrayList<>();
        String resourcesPath = "src/main/java/resources/";
        String[] imageFiles = {
            "生成校园歌唱比赛图片.png",
            "生成校园歌唱比赛图片 (1).png",
            "生成校园歌唱比赛图片 (4).png",
            "生成校园歌唱比赛图片 (5).png",
            "生成校园歌唱比赛图片 (8).png"
        };

        // 尝试从文件系统加载图片
        for (String fileName : imageFiles) {
            File file = new File(resourcesPath + fileName);
            if (file.exists()) {
                backgroundImages.add(new Image(file.toURI().toString()));
            } else {
                // 如果本地文件不存在，尝试使用类路径加载
                try {
                    Image img = new Image(getClass().getResourceAsStream("/" + fileName));
                    if (!img.isError()) {
                        backgroundImages.add(img);
                    }
                } catch (Exception e) {
                    // 如果都加载失败，则使用默认图片（如果有）
                }
            }
        }

        // 如果没有加载到图片，添加一个占位图片
        if (backgroundImages.isEmpty()) {
            // 创建一个简单的占位图片
            Image placeholder = new Image("");
            backgroundImages.add(placeholder);
        }
    }
    
    /**
     * 获取比赛的背景图片
     */
    private Image getCompetitionBackgroundImage(Competition competition) {
        // 如果比赛有自定义背景图片，使用它
        if (competition.getBackgroundImagePath() != null) {
            try {
                File customImageFile = new File(competition.getBackgroundImagePath());
                if (customImageFile.exists()) {
                    return new Image(customImageFile.toURI().toString());
                }
            } catch (Exception e) {
                System.err.println("加载自定义背景图片出错: " + e.getMessage());
            }
        }
        
        // 否则使用默认的随机背景图片
        if (!backgroundImages.isEmpty()) {
            int index = Math.abs(competition.getId().hashCode()) % backgroundImages.size();
            return backgroundImages.get(index);
        }
        
        // 最后兜底的默认图片
        return new Image("");
    }

    /**
     * 创建比赛管理界面
     */
    private void createView() {
        VBox competitionsView = new VBox(20);
        competitionsView.setPadding(new Insets(20));
        competitionsView.setStyle("-fx-background-color: #f5f5f5;");

        // 操作按钮
        HBox buttonBox = new HBox(15);
        buttonBox.setAlignment(javafx.geometry.Pos.CENTER_LEFT);
        buttonBox.setPadding(new Insets(0, 0, 10, 0));

        Button addBtn = new Button("新建比赛");
        addBtn.setStyle("-fx-background-color: #4caf50; -fx-text-fill: white;");
        addBtn.setPrefWidth(120);
        addBtn.setOnAction(e -> showAddCompetitionDialog());

        Button editBtn = new Button("修改比赛");
        editBtn.setStyle("-fx-background-color: #ff9800; -fx-text-fill: white;");
        editBtn.setPrefWidth(120);
        editBtn.setOnAction(e -> showEditButtonTooltip());

        Button deleteBtn = new Button("删除比赛");
        deleteBtn.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");
        deleteBtn.setPrefWidth(120);
        deleteBtn.setOnAction(e -> showDeleteButtonTooltip());

        Button refreshBtn = new Button("刷新数据");
        refreshBtn.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white;");
        refreshBtn.setPrefWidth(120);
        refreshBtn.setOnAction(e -> refreshCompetitionList());

        buttonBox.getChildren().addAll(addBtn, editBtn, deleteBtn, refreshBtn);

        // 创建下拉式滚动条容器
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setPrefHeight(600);
        scrollPane.setFitToWidth(true);
        scrollPane.setStyle("-fx-background-color: transparent; -fx-border-color: transparent;");

        // 比赛卡片列表容器
        competitionListContainer = new VBox(15);
        competitionListContainer.setPadding(new Insets(10));
        competitionListContainer.setStyle("-fx-background-color: transparent;");

        // 将比赛卡片容器放入滚动条
        scrollPane.setContent(competitionListContainer);

        // 初始化比赛列表
        refreshCompetitionList();

        competitionsView.getChildren().addAll(buttonBox, scrollPane);
        this.view = competitionsView;
    }

    /**
     * 刷新比赛列表
     */
    private void refreshCompetitionList() {
        competitionListContainer.getChildren().clear();
        List<Competition> competitions = competitionManager.getAllCompetitions();
        
        if (competitions.isEmpty()) {
            // 显示空状态提示
            Label emptyLabel = new Label("暂无比赛数据，请点击'新建比赛'添加");
            emptyLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: #757575;");
            emptyLabel.setPadding(new Insets(50));
            emptyLabel.setAlignment(javafx.geometry.Pos.CENTER);
            competitionListContainer.getChildren().add(emptyLabel);
        } else {
            // 为每个比赛创建卡片
            for (int i = 0; i < competitions.size(); i++) {
                Competition competition = competitions.get(i);
                HBox card = createCompetitionCard(competition, i);
                competitionListContainer.getChildren().add(card);
            }
        }
    }

    /**
     * 创建比赛卡片
     */
    private HBox createCompetitionCard(Competition competition, int index) {
        HBox card = new HBox(0);
        card.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");
        card.setPrefHeight(180);
        
        // 添加悬停效果
        card.setOnMouseEntered(e -> {
            card.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.25), 15, 0, 0, 8);");
        });
        
        card.setOnMouseExited(e -> {
            card.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");
        });

        // 左侧图片区域
        ImageView imageView = new ImageView();
        // 使用比赛的背景图片（优先使用自定义图片）
        Image image = getCompetitionBackgroundImage(competition);
        imageView.setImage(image);
        imageView.setFitWidth(220);
        imageView.setFitHeight(180);
        imageView.setPreserveRatio(false);
        imageView.setStyle("-fx-background-radius: 10 0 0 10;");

        // 右侧信息区域
        VBox infoBox = new VBox(10);
        infoBox.setPadding(new Insets(20));
        infoBox.setPrefWidth(400);

        // 比赛名称
        Label nameLabel = new Label(competition.getName());
        nameLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: #212121;");

        // 比赛信息
        VBox detailsBox = new VBox(5);
        detailsBox.getChildren().addAll(
            createInfoLabel("比赛ID: " + competition.getId()),
            createInfoLabel("日期: " + competition.getDate()),
            createInfoLabel("等级: " + competition.getLevel()),
            createInfoLabel("评分规则: " + competition.getScoringRule())
        );
        
        // 显示是否使用了自定义图片
        if (competition.getBackgroundImagePath() != null) {
            Label customImageLabel = new Label("✓ 已使用自定义背景图片");
            customImageLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #4caf50; -fx-font-weight: bold;");
            detailsBox.getChildren().add(customImageLabel);
        }

        // 操作按钮
        HBox cardButtons = new HBox(10);
        cardButtons.setAlignment(javafx.geometry.Pos.CENTER_LEFT);
        
        Button editBtn = new Button("修改");
        editBtn.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white; -fx-pref-width: 80;");
        editBtn.setOnAction(e -> editCompetition(competition));
        
        Button deleteBtn = new Button("删除");
        deleteBtn.setStyle("-fx-background-color: #f44336; -fx-text-fill: white; -fx-pref-width: 80;");
        deleteBtn.setOnAction(e -> deleteCompetition(competition));

        cardButtons.getChildren().addAll(editBtn, deleteBtn);

        infoBox.getChildren().addAll(nameLabel, detailsBox, cardButtons);

        // 将图片和信息添加到卡片
        card.getChildren().addAll(imageView, infoBox);

        return card;
    }

    /**
     * 创建信息标签
     */
    private Label createInfoLabel(String text) {
        Label label = new Label(text);
        label.setStyle("-fx-font-size: 14px; -fx-text-fill: #616161;");
        return label;
    }

    /**
     * 显示编辑按钮提示
     */
    private void showEditButtonTooltip() {
        AlertUtil.showInfoAlert("提示", "请点击具体比赛卡片中的'修改'按钮编辑比赛");
    }

    /**
     * 显示删除按钮提示
     */
    private void showDeleteButtonTooltip() {
        AlertUtil.showInfoAlert("提示", "请点击具体比赛卡片中的'删除'按钮删除比赛");
    }

    /**
     * 显示添加比赛对话框
     */
    private void showAddCompetitionDialog() {
        Dialog<Competition> dialog = new Dialog<>();
        dialog.setTitle("新建比赛");
        dialog.setHeaderText("创建新比赛");
        dialog.getDialogPane().setStyle("-fx-background-color: #f5f5f5;");
        dialog.getDialogPane().setMinWidth(600);

        // 设置按钮类型
        ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);
        Button saveButton = (Button) dialog.getDialogPane().lookupButton(saveButtonType);
        saveButton.setStyle("-fx-background-color: #4caf50; -fx-text-fill: white;");
        Button cancelButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
        cancelButton.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");

        // 创建表单
        VBox mainContainer = new VBox(20);
        mainContainer.setPadding(new Insets(20));
        mainContainer.setAlignment(Pos.CENTER);

        // 左侧输入区域，右侧图片预览区域
        HBox contentBox = new HBox(20);
        contentBox.setAlignment(Pos.CENTER);
        contentBox.setPadding(new Insets(10));

        // 左侧表单
        GridPane grid = new GridPane();
        grid.setHgap(15);
        grid.setVgap(15);
        grid.setPadding(new Insets(10));

        // 设置表单样式
        grid.getStyleClass().add("form-grid");
        grid.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");

        // 表单字段
        TextField idField = new TextField();
        idField.setPromptText("比赛ID");
        idField.setPrefWidth(200);
        idField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        TextField nameField = new TextField();
        nameField.setPromptText("比赛名称");
        nameField.setPrefWidth(200);
        nameField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        TextField dateField = new TextField();
        dateField.setPromptText("日期 (YYYY-MM-DD)");
        dateField.setPrefWidth(200);
        dateField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        ComboBox<String> levelField = new ComboBox<>();
        levelField.getItems().addAll("校级", "院级", "省级", "国家级");
        levelField.setValue("校级");
        levelField.setPrefWidth(200);
        levelField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        ComboBox<String> ruleField = new ComboBox<>();
        ruleField.getItems().addAll("标准评分规则", "加权评分规则");
        ruleField.setValue("标准评分规则");
        ruleField.setPrefWidth(200);
        ruleField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        // 添加标签和字段到网格
        grid.add(new Label("比赛ID: *"), 0, 0);
        grid.add(idField, 1, 0);
        grid.add(new Label("比赛名称: *"), 0, 1);
        grid.add(nameField, 1, 1);
        grid.add(new Label("日期: *"), 0, 2);
        grid.add(dateField, 1, 2);
        grid.add(new Label("等级: *"), 0, 3);
        grid.add(levelField, 1, 3);
        grid.add(new Label("评分规则: *"), 0, 4);
        grid.add(ruleField, 1, 4);

        // 右侧图片上传和预览区域
        VBox imageBox = new VBox(15);
        imageBox.setAlignment(Pos.CENTER);
        imageBox.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");
        
        // 图片预览
        ImageView previewImageView = new ImageView();
        previewImageView.setFitWidth(180);
        previewImageView.setFitHeight(140);
        previewImageView.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");
        previewImageView.setPreserveRatio(true);
        previewImageView.setSmooth(true);
        
        // 上传按钮
        Button uploadButton = new Button("上传背景图片");
        uploadButton.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white; -fx-pref-width: 150;");
        
        // 存储上传的图片路径
        final String[] imagePath = {null};
        
        uploadButton.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择背景图片");
            fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp")
            );
            File selectedFile = fileChooser.showOpenDialog(dialog.getDialogPane().getScene().getWindow());
            
            if (selectedFile != null) {
                try {
                    // 创建存储图片的目录
                    File imagesDir = new File("user_uploads");
                    if (!imagesDir.exists()) {
                        imagesDir.mkdir();
                    }
                    
                    // 生成唯一的文件名
                    String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                    String extension = getFileExtension(selectedFile);
                    String newFileName = timestamp + "." + extension;
                    File destFile = new File(imagesDir, newFileName);
                    
                    // 复制文件
                    Files.copy(selectedFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    
                    // 保存相对路径
                    imagePath[0] = "user_uploads/" + newFileName;
                    
                    // 显示预览
                    previewImageView.setImage(new Image(destFile.toURI().toString()));
                    
                } catch (IOException ex) {
                    AlertUtil.showErrorAlert("上传失败", "图片上传出错: " + ex.getMessage());
                }
            }
        });

        // 添加说明文字
        Label imageDesc = new Label("可选：上传自定义背景图片");
        imageDesc.setStyle("-fx-font-size: 12px; -fx-text-fill: #666;");
        
        imageBox.getChildren().addAll(previewImageView, uploadButton, imageDesc);

        // 将表单和图片区域添加到内容框
        contentBox.getChildren().addAll(grid, imageBox);
        
        // 添加底部说明
        Label requiredNote = new Label("* 表示必填项");
        requiredNote.setStyle("-fx-font-size: 12px; -fx-text-fill: #ff6b6b;");
        requiredNote.setAlignment(Pos.CENTER_LEFT);
        
        mainContainer.getChildren().addAll(contentBox, requiredNote);
        
        dialog.getDialogPane().setContent(mainContainer);

        // 将结果转换为比赛对象
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == saveButtonType) {
                if (idField.getText().isEmpty() || nameField.getText().isEmpty() || dateField.getText().isEmpty()) {
                    AlertUtil.showErrorAlert("输入错误", "请填写所有必填字段");
                    return null;
                }
                Competition competition = new Competition(
                        idField.getText(),
                        nameField.getText(),
                        dateField.getText(),
                        levelField.getValue(),
                        ruleField.getValue()
                );
                
                // 设置背景图片路径
                if (imagePath[0] != null) {
                    competition.setBackgroundImagePath(imagePath[0]);
                }
                
                return competition;
            }
            return null;
        });

        // 显示对话框并处理结果
        dialog.showAndWait().ifPresent(competition -> {
            competitionManager.addCompetition(competition);
            refreshCompetitionList();
            AlertUtil.showInfoAlert("成功", "比赛已添加");
        });
    }
    
    /**
     * 获取文件扩展名
     */
    private String getFileExtension(File file) {
        String name = file.getName();
        int lastDotIndex = name.lastIndexOf(".");
        if (lastDotIndex > 0) {
            return name.substring(lastDotIndex + 1).toLowerCase();
        }
        return "";
    }

    /**
     * 编辑指定的比赛
     */
    private void editCompetition(Competition competition) {
        // 创建编辑比赛对话框
        Dialog<Competition> dialog = new Dialog<>();
        dialog.setTitle("修改比赛");
        dialog.setHeaderText("修改比赛信息");
        dialog.getDialogPane().setStyle("-fx-background-color: #f5f5f5;");
        dialog.getDialogPane().setMinWidth(600);

        // 设置按钮类型
        ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);
        Button saveButton = (Button) dialog.getDialogPane().lookupButton(saveButtonType);
        saveButton.setStyle("-fx-background-color: #4caf50; -fx-text-fill: white;");
        Button cancelButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
        cancelButton.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");

        // 创建表单
        VBox mainContainer = new VBox(20);
        mainContainer.setPadding(new Insets(20));
        mainContainer.setAlignment(Pos.CENTER);

        // 左侧输入区域，右侧图片预览区域
        HBox contentBox = new HBox(20);
        contentBox.setAlignment(Pos.CENTER);
        contentBox.setPadding(new Insets(10));

        // 左侧表单
        GridPane grid = new GridPane();
        grid.setHgap(15);
        grid.setVgap(15);
        grid.setPadding(new Insets(10));

        // 设置表单样式
        grid.getStyleClass().add("form-grid");
        grid.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");

        // 表单字段
        TextField idField = new TextField(competition.getId());
        idField.setDisable(true);
        idField.setPrefWidth(200);
        idField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        TextField nameField = new TextField(competition.getName());
        nameField.setPrefWidth(200);
        nameField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        TextField dateField = new TextField(competition.getDate());
        dateField.setPrefWidth(200);
        dateField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        ComboBox<String> levelField = new ComboBox<>();
        levelField.getItems().addAll("校级", "院级", "省级", "国家级");
        levelField.setValue(competition.getLevel());
        levelField.setPrefWidth(200);
        levelField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        ComboBox<String> ruleField = new ComboBox<>();
        ruleField.getItems().addAll("标准评分规则", "加权评分规则");
        ruleField.setValue(competition.getScoringRule());
        ruleField.setPrefWidth(200);
        ruleField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        // 添加标签和字段到网格
        grid.add(new Label("比赛ID: *"), 0, 0);
        grid.add(idField, 1, 0);
        grid.add(new Label("比赛名称: *"), 0, 1);
        grid.add(nameField, 1, 1);
        grid.add(new Label("日期: *"), 0, 2);
        grid.add(dateField, 1, 2);
        grid.add(new Label("等级: *"), 0, 3);
        grid.add(levelField, 1, 3);
        grid.add(new Label("评分规则: *"), 0, 4);
        grid.add(ruleField, 1, 4);

        // 右侧图片上传和预览区域
        VBox imageBox = new VBox(15);
        imageBox.setAlignment(Pos.CENTER);
        imageBox.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");
        
        // 图片预览
        ImageView previewImageView = new ImageView();
        previewImageView.setFitWidth(180);
        previewImageView.setFitHeight(140);
        previewImageView.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");
        previewImageView.setPreserveRatio(true);
        previewImageView.setSmooth(true);
        
        // 显示当前背景图片（如果有）
        if (competition.getBackgroundImagePath() != null) {
            try {
                File currentImageFile = new File(competition.getBackgroundImagePath());
                if (currentImageFile.exists()) {
                    previewImageView.setImage(new Image(currentImageFile.toURI().toString()));
                }
            } catch (Exception e) {
                System.err.println("加载当前背景图片出错: " + e.getMessage());
            }
        }
        
        // 存储上传的图片路径（初始为当前路径）
        final String[] imagePath = {competition.getBackgroundImagePath()};
        
        // 上传按钮
        Button uploadButton = new Button("上传背景图片");
        uploadButton.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white; -fx-pref-width: 150;");
        
        uploadButton.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择背景图片");
            fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp")
            );
            File selectedFile = fileChooser.showOpenDialog(dialog.getDialogPane().getScene().getWindow());
            
            if (selectedFile != null) {
                try {
                    // 创建存储图片的目录
                    File imagesDir = new File("user_uploads");
                    if (!imagesDir.exists()) {
                        imagesDir.mkdir();
                    }
                    
                    // 生成唯一的文件名
                    String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                    String extension = getFileExtension(selectedFile);
                    String newFileName = timestamp + "." + extension;
                    File destFile = new File(imagesDir, newFileName);
                    
                    // 复制文件
                    Files.copy(selectedFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    
                    // 保存相对路径
                    imagePath[0] = "user_uploads/" + newFileName;
                    
                    // 显示预览
                    previewImageView.setImage(new Image(destFile.toURI().toString()));
                    
                } catch (IOException ex) {
                    AlertUtil.showErrorAlert("上传失败", "图片上传出错: " + ex.getMessage());
                }
            }
        });

        // 移除背景图片按钮
        Button removeImageButton = new Button("移除背景图片");
        removeImageButton.setStyle("-fx-background-color: #ff9800; -fx-text-fill: white; -fx-pref-width: 150;");
        removeImageButton.setOnAction(e -> {
            imagePath[0] = null;
            previewImageView.setImage(null);
        });
        
        // 添加说明文字
        Label imageDesc = new Label("可选：修改比赛的背景图片");
        imageDesc.setStyle("-fx-font-size: 12px; -fx-text-fill: #666;");
        
        imageBox.getChildren().addAll(previewImageView, uploadButton, removeImageButton, imageDesc);

        // 将表单和图片区域添加到内容框
        contentBox.getChildren().addAll(grid, imageBox);
        
        // 添加底部说明
        Label requiredNote = new Label("* 表示必填项");
        requiredNote.setStyle("-fx-font-size: 12px; -fx-text-fill: #ff6b6b;");
        requiredNote.setAlignment(Pos.CENTER_LEFT);
        
        mainContainer.getChildren().addAll(contentBox, requiredNote);
        
        dialog.getDialogPane().setContent(mainContainer);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == saveButtonType) {
                if (nameField.getText().isEmpty() || dateField.getText().isEmpty()) {
                    AlertUtil.showErrorAlert("输入错误", "请填写所有必填字段");
                    return null;
                }
                Competition updatedCompetition = new Competition(
                        idField.getText(),
                        nameField.getText(),
                        dateField.getText(),
                        levelField.getValue(),
                        ruleField.getValue()
                );
                
                // 设置背景图片路径
                updatedCompetition.setBackgroundImagePath(imagePath[0]);
                
                return updatedCompetition;
            }
            return null;
        });

        dialog.showAndWait().ifPresent(updatedCompetition -> {
            competitionManager.updateCompetition(updatedCompetition);
            refreshCompetitionList();
            AlertUtil.showInfoAlert("成功", "比赛已更新");
        });
    }

    /**
     * 删除指定的比赛
     */
    private void deleteCompetition(Competition competition) {
        // 确认对话框
        Alert confirm = new Alert(Alert.AlertType.CONFIRMATION);
        confirm.setTitle("确认删除");
        confirm.setHeaderText("确定要删除此比赛吗？");
        confirm.setContentText("比赛ID: " + competition.getId() + "\n比赛名称: " + competition.getName() + 
                             "\n\n注意：删除比赛将同时删除所有相关的队伍和评分记录！");

        confirm.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                System.out.println("确认删除比赛: " + competition.getId());
                
                // 使用级联删除，同时删除相关队伍和评分
                boolean deleted = competitionManager.deleteCompetitionWithCascade(competition.getId(), scoreManager, teamManager);
                
                if (deleted) {
                    System.out.println("比赛删除成功，刷新界面");
                    refreshCompetitionList();
                    AlertUtil.showInfoAlert("成功", "比赛及相关队伍、评分记录已删除");
                } else {
                    System.err.println("比赛删除失败");
                    AlertUtil.showErrorAlert("错误", "删除比赛失败，请重试");
                }
            }
        });
    }

    /**
     * 获取界面视图
     */
    public VBox getView() {
        return view;
    }
}